package com.crl.nfp.util;

import com.crl.nfp.log.model.LogModel;
import com.cars.util.string.StringUtil;
import org.springframework.util.MimeTypeUtils;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;

/**
 * 工具
 *
 * @author 宋长军
 * @date 2020/4/13 9:32
 */
public class RequestUtil {

    /**
     * 获取请求参数
     *
     * @param request 请求
     * @return 参数
     */
    public static String getRequestParams(HttpServletRequest request) {
        String params = "";
        try {
            String contextType = request.getContentType();
            if (!StringUtils.isEmpty(contextType)
                    && contextType.contains(MimeTypeUtils.APPLICATION_JSON_VALUE)) {
                params = StringUtil.getBodyString(request.getReader());
            } else {
                params = StringUtil.getRequestParamMap(request).toString();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return params;
    }

    /**
     * 设置响应时间，请求耗时
     *
     * @param logModel 日志相关信息
     */
    public static void setTimeConsuming(LogModel logModel) {

        Date requestDate = logModel.getRequestDate();
        Date responseDate = new Date();
        if (requestDate != null) {
            logModel.setTimeConsuming(
                    responseDate.getTime() - requestDate.getTime());
        }
        logModel.setResponseDate(responseDate);
    }
}
